use super::{json, ok, Client, Resp, VMap, VRece, VSend};
use std::time::Instant;
use tracing::{instrument, warn};

#[instrument(skip_all, name = "queue_chunk")]
pub async fn queue_chunk(rx: &VRece, tx: VSend, client: &Client) {
    loop {
        let _ = do_buffer(rx, &tx, client).await;
    }
}

#[instrument(skip_all, name = "buffer")]
async fn do_buffer(rx: &VRece, tx: &VSend, client: &Client) -> Resp {
    if let Ok(d) = rx.recv().await {
        let start = Instant::now();

        warn!("buf len: {:?}", rx.len());

        let q = d.ck_str("q")?;
        let db = d.ck_str("db")?;

        if let Err(e) = client.send_write(q, db).await {
            let duration = start.elapsed();
            let info = format!("check time: {:?}\terror: {:?}\tdata: {:?}", duration, e, d);
            warn!("{}", &info);

            if let Some(_) = info.find("timeout") {
                let _ = tx.send(d).await;
            }
        } else {
            let duration = start.elapsed();
            warn!("chunk time: {:?}", duration);
        }
    }

    ok!()
}
